package com.itany.shop.factory;

import com.itany.shop.exception.ObjectFactoryErrorException;
import com.itany.shop.util.JDBCTemplate;
import com.itany.shop.util.ParameterUtil;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author MissChen
 * @date 2024年03月29日 8:45
 */
public class ObjectFactory {
    private static Map<String,Object> objs;
    static{
        objs=new HashMap<>();
        BufferedReader br=null;
        try {
            br=new BufferedReader(new InputStreamReader(
                    ObjectFactory
                            .class
                            .getClassLoader()
                            .getResourceAsStream("beans.properties"))
            );
            String line=null;
            while((line=br.readLine())!=null){
                if(!ParameterUtil.isNull(line)){
                    String[] arr=line.split("=");
                    String key=arr[0];
                    String value=arr[1];
                    objs.put(key,Class.forName(value).newInstance());
                }
            }
        } catch (Exception e) {
                e.printStackTrace();
                throw new ExceptionInInitializerError("ObjectFactory初始化失败");
        }finally {
            if(br!=null){
                try {
                    br.close();
                } catch (IOException e) {
                   throw new ExceptionInInitializerError("释放资源失败");
                }
            }
        }
    }
    public static Object getObject(String key){
        Object obj=objs.get(key);
        if(null==obj){
            throw new ObjectFactoryErrorException("根据指定的key:"+key+"在配置文件中没有找到对应的配置");
        }
        return obj;
    }

    public static void main(String[] args) {
        JDBCTemplate jdbcTemplate= (JDBCTemplate) ObjectFactory.getObject("aaa");
        System.out.println(jdbcTemplate);


    }

}
